package com.xyh.web.admin;

import com.xyh.pojo.User;
import com.xyh.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class LoginController {
    @Autowired
    private UserService service;
    @GetMapping
    public String loginPage(){
        return "admin/login";
    }
    @GetMapping("/forget-password")
    public String forgetPasswordPage(){
        return "admin/forget-password";
    }
    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password, HttpSession session, RedirectAttributes attributes){
        User user = service.checkUser(username, password);
        if (user!=null) {
            user.setPassword(null);
            session.setAttribute("user",user);
            return "admin/index";
        }else {
            attributes.addFlashAttribute("message","用户名或密码错误！");
            return "redirect:/admin";
//            return "admin/login";
        }
    }
    @PostMapping("/update-password")
    public String updatePassword(String password, RedirectAttributes attributes){
        System.out.println(password);
        int update=service.updatePassword(password);
        if (update==1) {
            attributes.addFlashAttribute("message","密码更改成功，请重新登陆！");
        }else {
            attributes.addFlashAttribute("message","密码更改失败！");
        }
        return "redirect:/admin";
    }
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/admin";
    }
}
